package leetcode.p1449;

import java.util.Arrays;

/**
 * @author: trtan
 * @date: 2021-06-12 15:14
 **/
public class AddUpToTarget {
    public static void main(String[] args) {
        int[] cost = new int[]{4,3,2,5,6,7,2,5,5};
        String s = new AddUpToTarget().largestNumber(cost, 9);
        System.out.println(s);
    }
    public String largestNumber(int[] cost, int target) {
        // dp[i][j] 代表前i种数字，花费为j最长是多长
        // 第i个数字不取
        //dp[i][j] = dp[i - 1][j];
        // 第i个数字取
        //dp[i][j] = dp[i - 1][j - cost[i]] + 1;
        // 第i个数字可能取多次
        //dp[i][j] = dp[i][j - cost[i]] + 1;
        //=> 三种情况取最大值 由于dp[i][j - cost[i]] 包含了dp[i - 1][j - cost[i]] 花费为j-cost[i]时第i个不取的情况
        // 故 dp[i][j] = max(dp[i - 1][j], dp[i][j - cost[i]] + 1)
        int[][] dp = new int[cost.length + 1][target + 1];
        // 初始化为无穷小
        for (int i = 0; i < dp.length; i++) {
            Arrays.fill(dp[i], Integer.MIN_VALUE);
        }
        // from[i][j] 表示dp[i][j]是由多少花费转移来的
        int[][] from = new int[cost.length + 1][target + 1];
        dp[0][0] = 0;
        for (int i = 1; i <= cost.length; i++) {
            for (int j = 0; j <= target; j++) {
                if (j <cost[i - 1]) {
                    // 第i个数字取不了
                    dp[i][j] = dp[i - 1][j];
                    from[i][j] = j;
                } else {
                    if (dp[i - 1][j] <= dp[i][j - cost[i - 1]] + 1) {
                        dp[i][j] = dp[i][j - cost[i - 1]] + 1;
                        from[i][j] = j - cost[i - 1];
                    } else {
                        dp[i][j] = dp[i - 1][j];
                        from[i][j] = j;
                    }
                }

            }
        }
        if (dp[cost.length][target] <= 0) {
            return "0";
        }
        StringBuilder result = new StringBuilder();
        for (int i = cost.length; i >= 1; i--) {
            while (target >= cost[i - 1] && dp[i][target] == dp[i][target - cost[i - 1]] + 1) {
                result.append(i);
                target = target - cost[i - 1];
            }
        }
//        for (int i = cost.length; i >= 1; i--) {
//            while (target > 0) {
//                if (target == from[i][target]) {
//                    break;
//                }
//                target = from[i][target];
//                result.append(i);
//            }
//        }
        return result.toString();
    }

}
